package au.edu.unsw.editingtool.web;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Hashtable;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import au.edu.unsw.editingtool.db.DBEditingpool;
import au.edu.unsw.editingtool.global.EditingToolGlobalConstant;
import au.edu.unsw.editingtool.global.EditingToolPropertyReader;
import au.edu.unsw.editingtool.transformxml.ValetXmlCreator;

/**
 * Servlet implementation class FormCommit
 */
public class FormCommit extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FormCommit() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doService(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doService(request, response);
	}

	private void updateStatus(boolean isAttachment, String pid) throws SQLException, ClassNotFoundException {
		if (!isAttachment) {
			DBEditingpool editingpool = new DBEditingpool();
			editingpool.changeAsSubmit(pid);
		}
	}
	
	protected void doService(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		// get data, commit in using fedora, and save record in the database.
		
		String servletContext = getServletContext().getRealPath("") + EditingToolGlobalConstant.fileSeparator;
		
		if (req.getParameter(EditingToolGlobalConstant.buttonTypeCancel) != null)
			res.sendRedirect("logout.jsp");
		else {
			ValetXmlCreator valetXML = new ValetXmlCreator();
			// check the sessionid and username
			
			String cmd = req.getParameter(EditingToolGlobalConstant.requestCommandType);
			String element = "";
			if (cmd.equals(EditingToolGlobalConstant.commandPreview)) {
				valetXML.createValetDocument("Session");
				valetXML.createFormDataElement();
				Hashtable<String, String> formData = new Hashtable<String, String>();
				
				for (Enumeration<String> e = req.getParameterNames(); e.hasMoreElements(); ) {
					element = (String) e.nextElement();
					if (element.equals(EditingToolGlobalConstant.requestCommand))
						continue;
					else if (element.equals(EditingToolGlobalConstant.requestUsername))
						continue;
					else if (element.equals(EditingToolGlobalConstant.requestSessionID))
						continue;
					else if (element.equals(EditingToolGlobalConstant.buttonTypeCancel))
						continue;
					else if (element.equals(EditingToolGlobalConstant.buttonTypeSubmit))
						continue;
					else {
						formData.put(element, req.getParameter(element));
					}
				}
				
				valetXML.createChildElementsWithContentsUsingHashtable(formData, EditingToolGlobalConstant.valetDocFormData);
				
				EditingToolPropertyReader reader = new EditingToolPropertyReader();
				reader.setFile(servletContext + EditingToolGlobalConstant.configFilePath);
				reader.setFilter(EditingToolPropertyReader.FEDORA);
				reader.retrieveProperties();
				Hashtable<String, String> properties = reader.getProperties();
				
				String fedoraHost = properties.get("host") + ":" + properties.get("port") + properties.get("path");
				String username   = properties.get("username");
				String password   = properties.get("password");
				String dataStream = properties.get("datastream");
				
				properties.clear();
				reader.clean();
				reader.setFilter(EditingToolPropertyReader.DATASTREAM);
				reader.retrieveProperties();
				properties = reader.getProperties();
				String xsl = properties.get("root") + EditingToolGlobalConstant.fileSeparator +
				 			 properties.get("name") + EditingToolGlobalConstant.fileSeparator + 
				 			 properties.get("tovalet");
				
				valetXML.fedoraUpdateMetadata(fedoraHost, username, password, 
									  		  req.getParameter(EditingToolGlobalConstant.requestPid), 
									  		  dataStream, xsl);
				try {
					this.updateStatus(false, req.getParameter(EditingToolGlobalConstant.requestPid));
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {
				
			}
			
			
		}
	}
}
